from .io_operation import BasicIo
from .oil_pressure_check import OilPressureCheck
import time
import gevent


class Lubrication:
    """
    润滑操作
    """
    IDLE = 0
    CAMMAND_SENDED = 1
    OIL_PRESSURE_CHECK = 2
    OIL_SUPPLY = 3

    def __init__(self, elapsed_time=20, channel_index=None):
        super(Lubrication, self).__init__()
        self._current_step = self.IDLE
        self._force_abort = False
        if channel_index is None:
            self.lubrication_io = BasicIo("Lubrication")
            self.oil_io = OilPressureCheck("OilIo")
        else:
            self.lubrication_io = BasicIo("Lubrication_ch%d" % channel_index)
            self.oil_io = OilPressureCheck("OilIo_ch%d" % channel_index)
        self.elapsed_time = elapsed_time

    def start(self):
        """
        开始执行润滑操作
        """
        self._force_abort = False
        gevent.spawn(self._start)

    def _start(self):
        while True:
            if self._current_step == self.IDLE:
                self._current_step = self.CAMMAND_SENDED

            elif self._current_step == self.CAMMAND_SENDED:
                self.lubrication_io.set_true()
                self._current_step = self.OIL_PRESSURE_CHECK

            elif self._current_step == self.OIL_PRESSURE_CHECK:
                if self._force_abort is True:  # 强制退出
                    self._current_step = self.IDLE
                    break

                _stop_time = time.time() + self.elapsed_time
                if time.time() > _stop_time:  # 超时退出
                    self._current_step = self.IDLE
                    self.lubrication_io.set_false()
                    break

                oil_is_ok = self.oil_io.read_state()
                if oil_is_ok:
                    self._current_step = self.OIL_SUPPLY

            elif self._current_step == self.OIL_SUPPLY:
                if self._force_abort is True:  # 强制退出
                    self._current_step = self.IDLE
                    break

                _stop_time = time.time() + self.elapsed_time
                if time.time() > _stop_time:  # 供油时间到
                    self._current_step = self.IDLE
                    self.lubrication_io.set_false()
                    break

            gevent.sleep(0.01)

    def stop(self):
        self._force_abort = True
        self.lubrication_io.set_false()

    def is_ongoing(self):
        if self._current_step == self.IDLE:
            return False

        if not self.lubrication_io.read_state():
            print("未在工作")
            return False

        if self.oil_io.read_state():
            print("正在工作")
            return True
        else:
            print("未在工作, 油压异常")
            return False
